﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
using System.Xml;

namespace Comm.PublicClass
{
    public class RWOutFiles
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key,
        string def, StringBuilder retVal,
        int size, string filePath);

        [DllImport("kernel32")]
        public static extern uint GetPrivateProfileString(string section, string key,
        string def, Byte[] retVal,
        int size, string filePath);

        /// <summary>
        /// 写INI文件数据
        /// </summary>
        /// <param name="filename">带路径的文件名</param>
        /// <param name="section">段名</param>
        /// <param name="Key">关键字</param>
        /// <param name="Value">数据值</param>
        public static void WriteINIString(string filename, string section, string Key, string Value)
        {
            WritePrivateProfileString(section, Key, Value, filename);
        }

        /// <summary>
        /// 得到INI文件数据
        /// </summary>
        /// <param name="filename">带路径的文件名</param>
        /// <param name="section">段名</param>
        /// <param name="Key">关键字</param>
        /// <param name="defaultstring">如未找到返回的默认值</param>
        /// <returns>取犁关键字数据值</returns>
        public static string GetINIString(string filename, string section, string key, string defaultstring)
        {
            int iTmp = 0;
            StringBuilder strTmp = new StringBuilder(1024);
            try
            {
                iTmp = GetPrivateProfileString(section, key, "",
                strTmp, 1024, filename);
                string rs = strTmp.ToString();
                if (string.IsNullOrEmpty(rs))
                    rs = defaultstring;
                return rs;
            }
            catch (Exception ex)
            {
                return defaultstring;
            }
        }

        /// <summary>
        /// 获取INI文件中的所有section
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static List<string> GetSections(string filename)
        {
            List<string> rs = new List<string>();
            Byte[] strTmp = new Byte[10485760];  //10M
            uint len = GetPrivateProfileString(null, null, null, strTmp, strTmp.Length, filename);
            int j = 0;
            for (int i = 0; i < len; i++)
            {
                if (strTmp[i] == 0)
                {
                    rs.Add(Encoding.Default.GetString(strTmp, j, i - j));
                    j = i + 1;
                }
            }
            return rs;
        }

        /// <summary>
        /// 获取INI文件中某个section下的所有key
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="SectionName"></param>
        /// <returns></returns>
        public static List<string> ReadKeys(string filename, string SectionName)
        {
            List<string> result = new List<string>(); 
            Byte[] buf = new Byte[65536];
            uint len = GetPrivateProfileString(SectionName, null, null, buf, buf.Length, filename);
            int j = 0;
            for (int i = 0; i < len; i++)
                if (buf[i] == 0)
                {
                    result.Add(Encoding.Default.GetString(buf, j, i - j));
                    j = i + 1;
                }
            return result;
        }

        /// <summary>
        /// XML文件导入成Dataset
        /// </summary>
        /// <param name="fromPath">带路径的文件名</param>
        /// <returns>DataSet数据集</returns>
        public static DataSet XmlToDataSet(string fromPath)
        {
            try
            {
                FileInfo xmlFile = new FileInfo(fromPath);
                DataSet dsXML = null;
                if (xmlFile.Exists)
                {
                    FileStream fsReadXml = new FileStream(fromPath, FileMode.Open);
                    XmlTextReader myXmlReader = new XmlTextReader(fsReadXml);
                    dsXML = new DataSet();
                    dsXML.ReadXml(myXmlReader);
                    myXmlReader.Close();
                }
                return dsXML;
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// Dataset导出成XML文件
        /// </summary>
        /// <param name="ds">需导出数据的DataSet数据集</param>
        /// <param name="strXMLPath">带路径的文件名</param>
        /// <returns>true:成功； false：失败</returns>
        public static bool DataSetToXMl(DataSet ds, string strXMLPath)
        {
            bool bReturnValue = false;
            try
            {
                FileInfo XMLfile = new FileInfo(strXMLPath);
                if (!XMLfile.Exists)
                {
                    FileStream myFs = new FileStream(strXMLPath, FileMode.Create);
                    StreamWriter mySw = new StreamWriter(myFs);
                    mySw.Write("");
                    mySw.Close();
                    myFs.Close();
                    XMLfile = new FileInfo(strXMLPath);
                }
                if (ds != null && ds.Tables.Count > 0)
                {
                    ds.WriteXml(strXMLPath, XmlWriteMode.WriteSchema);
                    bReturnValue = true;
                }
            }
            catch
            {
                bReturnValue = false;
            }
            return bReturnValue;
        }

        /// <summary>
        /// Dataset导出成XML文件
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="strXMLPath"></param>
        /// <returns></returns>
        public static bool DataSetToXMl(DataSet ds, string strXMLPath, ref string errinfo)
        {
            string newpatch = Path.GetDirectoryName(strXMLPath);


            if (!Directory.Exists(newpatch))
            {
                Directory.CreateDirectory(newpatch);
            }
            bool bReturnValue = false;
            try
            {
                FileInfo XMLfile = new FileInfo(strXMLPath);
                if (!XMLfile.Exists)
                {
                    FileStream myFs = new FileStream(strXMLPath, FileMode.Create);
                    StreamWriter mySw = new StreamWriter(myFs);
                    mySw.Write("");
                    mySw.Close();
                    myFs.Close();
                    XMLfile = new FileInfo(strXMLPath);
                }
                if (ds != null && ds.Tables.Count > 0)
                {
                    ds.WriteXml(strXMLPath, XmlWriteMode.WriteSchema);
                    bReturnValue = true;
                }
            }
            catch (Exception ex)
            {
                bReturnValue = false;
                errinfo = ex.Message;
            }
            return bReturnValue;
        }

        /// <summary>
        /// XML文件导入成Dataset
        /// </summary>
        /// <param name="fromPath"></param>
        /// <returns></returns>
        public static DataSet XmlToDataSet(string fromPath, ref string errinfo)
        {
            FileInfo xmlFile = new FileInfo(fromPath);
            DataSet dsXML = null;
            try
            {
                if (xmlFile.Exists)
                {
                    FileStream fsReadXml = new FileStream(fromPath, FileMode.Open);
                    XmlTextReader myXmlReader = new XmlTextReader(fsReadXml);
                    dsXML = new DataSet();
                    dsXML.ReadXml(myXmlReader);
                    myXmlReader.Close();
                }
            }
            catch (Exception ex)
            {
                dsXML = null;
                errinfo = ex.Message;
            }
            return dsXML;
        }


        /// <summary>
        /// Dataset导出成XML字符串
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="strXMLPath"></param>
        /// <returns></returns>
        public static string DataSetToXMlStr(DataSet ds, ref string errinfo)
        {
            string bReturnValue = string.Empty;
            MemoryStream ms = new MemoryStream();
            XmlTextWriter xmlwt = new XmlTextWriter(ms, Encoding.Unicode);
            try
            {
                //获取ds中的数据
                if (ds != null && ds.Tables.Count > 0)
                {
                    ds.WriteXml(xmlwt);
                    int count = (int)ms.Length;
                    byte[] temp = new byte[count];
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Read(temp, 0, count);

                    //返回Unicode编码的文本
                    UnicodeEncoding ucode = new UnicodeEncoding();
                    bReturnValue = ucode.GetString(temp).Trim();
                }

            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
            }
            finally
            {
                //释放资源
                if (xmlwt != null)
                {
                    xmlwt.Close();
                    ms.Close();
                    ms.Dispose();
                }
            }
            return bReturnValue;
        }


        /// <summary>
        /// XML字符串导入成Dataset
        /// </summary>
        /// <param name="fromPath"></param>
        /// <returns></returns>
        public static DataSet XmlStrToDataSet(string xmlstr, ref string errinfo)
        {
            StringReader stream = null;
            XmlTextReader myXmlReader = null;
            DataSet dsXML = null;
            try
            {
                if (!string.IsNullOrEmpty(xmlstr))
                {
                    stream = new StringReader(xmlstr);
                    myXmlReader = new XmlTextReader(stream);
                    dsXML = new DataSet();
                    dsXML.ReadXml(myXmlReader);
                    myXmlReader.Close();
                }
            }
            catch (Exception ex)
            {
                dsXML = null;
                errinfo = ex.Message;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();

                }
                if (myXmlReader != null)
                {
                    myXmlReader.Close();

                }
            }
            return dsXML;
        }
             
        /// <summary>
        /// 获取文件夹下的所有文件 shaunwang 2016-5-30
        /// </summary>
        /// <param name="filePath">目标文件夹</param>
        /// <param name="fExt">后缀名  多个后缀名以逗号分隔  例 .bmp,.png</param>
        /// <returns></returns>
        public static List<string> GetFileInfo(string filePath, string fExt)
        {
            List<string> all = new List<string>();
            string[] extlst = fExt.ToUpper().Split(',');
            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            try
            {
                foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                {
                    if (extlst.Length > 0)
                    {
                        for (int i = 0; i < extlst.Length; i++)
                        {
                            if (fileInfo.Name.ToString().ToUpper().EndsWith(extlst[i]))
                            {
                                all.Add(fileInfo.Name.ToString());
                                break;
                            }
                        }
                    }
                    else
                        all.Add(fileInfo.Name.ToString());
                }

            }
            catch
            {

            }
            return all;
        }

        /// <summary>
        /// 写文件 add by xd
        /// </summary>
        /// <param name="fileinfo">文件内容</param>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        public static bool FileInfoSave(string fileinfo, string filepath)
        {
            try
            {
                StreamWriter stream = new StreamWriter(filepath, false, Encoding.Default);
                stream.Write(fileinfo);
                stream.Close();
                return true;
            }
            catch 
            {
                return false;
            }


        }
    }
}
